<template>
  <ul class="list-container">
    <li
      v-for="(item, index) in listItems"
      :key="index"
      :class="{ selected: selectedItems.includes(index) }"
      @click="toggleSelection(index)"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script setup>
import { ref } from 'vue';

// 通过props接收列表项数据
const props = defineProps({
  listItems: {
    type: Array,
    required: true
  }
});

// 用于存储已选中的项目
const selectedItems = ref([0]);

// 切换项目的选中状态
const toggleSelection = (num) => {
  const index = selectedItems.value.indexOf(num);
  if (index === -1) {
    selectedItems.value.push(num);
  } else if (selectedItems.value.length > 1) {
    selectedItems.value.splice(index, 1);
  }
  // 触发向外传递已选项目的事件
  emit('item-change', selectedItems.value);
};

// 定义事件
const emit = defineEmits(['item-change']);
</script>

<style scoped>
.list-container {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 6px;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  border-radius: 4px;
}

li:hover,
li.selected {
  background-color: #135369;
  color: #fff;
}
</style>